require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class LayerKeystrokeCount
  NAME = "Normalized Individual Keystroke Count" +
  "(Total number of keystrokes for each phrase, divided by number of characters in phrase)"
  
  def analyze(directory, experimentalData, phraseCards)

    #create the report
    report = Report.new(directory, NAME )

    #get the data by layer
    data = experimentalData.group_by_layer

    data.each_pair do |layer, entries|
      data_by_uid = {}

      entries.each do |e|
        #initialize if nil
        data_by_uid[e.uid] ||= []
        data_by_uid[e.uid] << e
      end

      #create a graph for each layer
      g = create_graph(layer)

      #do some simple statistics
      stat = ""

      #Generate a section for each tech uid
      data_by_uid.each_pair do |uid, entries|
        entries.sort! { |x,y| x.date <=> y.date }

        counts = entries.collect do |e|
          e.sequence.length.to_f / phraseCards.getPhrase(e.set, e.phrase).length
        end   
        
        avg = counts.inject{ |sum, el| sum + el }.to_f / counts.length  
          
        g.data "Subject:#{uid}", counts
        stat = stat + "<b>UID #{uid}:</b> " +
        "finished(phrases):#{entries.length} " +
        "average no of keystrokes (normalized): #{avg}" +
        "<br/>" 
      end

      report.new_section("Layer #{layer}", stat, g)
    end

    #generate report
    report.to_html
  end

  def create_graph (layer)
    g = Gruff::Line.new
    g.dot_radius = 2
    g.line_width = 2
    g.x_axis_label = "Phrases"
    g.y_axis_label = "Count (normalized)"
    g.title = "Keystroke Count (Layer:#{layer})"
    g
  end
end